package com.mysen.sso.controller;

import java.util.Set;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mysen.model.Pagenation;
import com.mysen.model.Response;
import com.mysen.sso.model.Role;
import com.mysen.sso.model.User;
import com.mysen.sso.service.UserService;

@Controller
public class UserController {
	
	@Reference
	private UserService service;
	
	@PostMapping("/user")
	@ResponseBody
	public Response<User> saveUser(@RequestBody User user){
		Response<User> resp = new Response<User>();
		user = service.save(user);
		resp.setSuccess(true);
		resp.setData(user);
		return resp;
	}
	
	@PostMapping("/users")
	@ResponseBody
	public Response<?> queryByPage(@RequestBody User user){
		Pagenation page = user.getPage();
		if(page == null) {
			page = new Pagenation(0, 10);
			user.setPage(page);
		}
		return service.selectByPage(user);
	}
	
	@PutMapping("/user/{id}")
	@ResponseBody
	public Response<User> updateUser(@RequestBody User user, @PathVariable("id") String userId){
		Response<User> resp = new Response<User>();
		user.setUserId(userId);
		service.updateById(user);
		resp.setData(user);
		resp.setSuccess(true);
		return resp;
	}
	
	@GetMapping("/user/{id}")
	@ResponseBody
	public Response<User> getUser(@PathVariable("id") String userId){
		Response<User> resp = new Response<User>();
		resp.setData(service.selectById(userId));
		resp.setSuccess(true);
		return resp;
	}
	
	@DeleteMapping("/user/{id}")
	@ResponseBody
	public Response<Role> delete(@PathVariable("id") String userId){
		Response<Role> resp = new Response<Role>();
		service.deleteById(userId);
		resp.setSuccess(true);
		return resp;
	}
	
	@PostMapping("/user/roles/{id}")
	@ResponseBody
	public Response<Role> addRoles(@PathVariable("id") String userId, Set<Role> roles){
		Response<Role> resp = new Response<Role>();
		User user = new User();
		user.setUserId(userId);
		user.setRoles(roles);
		service.addRoles(user);
		resp.setSuccess(true);
		return resp;
	}
}
